//    Copyright (C) Clear Office.  All rights reserved.
using System;
using System.IO;

namespace Office.Spreadsheet.Formats.Biff.Records
{
    internal sealed class SupportingWorkbook : WorkbookLevelRecord
    {
        private string[] _tabNames = new string[0];
        private bool _isSelfReferencing;

        string _virtualPath = null;

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.SupBook; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            throw new System.NotImplementedException();
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            ushort tabCount = context.ReadUInt16();
            ushort characterCount = context.ReadUInt16();
            bool isVirtualPath = false;
            bool isExternalWorkbookReferencing = false;
            bool isUnusedSupportingLink = false;
            bool isAddinReferencing;
            if (characterCount == 0x401)
            {
                _isSelfReferencing = true;
            }
            else if (characterCount == 0x3a01)
            {
                isAddinReferencing = true;
            }
            else if ((characterCount >= 1) && (characterCount <= 0xff))
            {
                isVirtualPath = true;
            }
            if (isVirtualPath)
            {
                _virtualPath = "";
                int i1 = context.ReadByte() & 1;
                for (int i = 0; i < characterCount; i++)
                {
                    if (i1 == 0)
                    {
                        _virtualPath = _virtualPath + ((char) context.ReadByte());
                    }
                    else
                    {
                        _virtualPath = _virtualPath + BitConverter.ToChar(context.ReadBytes(2), 0);
                    }
                }
                _virtualPath = parseVirtualPath(_virtualPath);
            }
            if (_virtualPath != null)
            {
                if (_virtualPath.Equals(0))
                {
                    _isSelfReferencing = true;
                }
                else if (_virtualPath.Equals(0x20))
                {
                    isUnusedSupportingLink = true;
                }
                else
                {
                    isExternalWorkbookReferencing = true;
                }
            }
            if (isExternalWorkbookReferencing || isUnusedSupportingLink)
            {
                _tabNames = new string[tabCount];
                for (int j = 0; j < tabCount; j++)
                {
                    ushort uInt16 = context.ReadUInt16();
                    int i = context.ReadByte() & 1;
                    for (int k = 0; k < uInt16; k++)
                    {
                        if (i == 0)
                        {
                            string[] strArray;
                            IntPtr ptr;
                            (strArray = _tabNames)[(int) (ptr = (IntPtr) j)] = strArray[(int) ptr] +
                                                                               ((char) context.ReadByte());
                        }
                        else
                        {
                            string[] strArray2;
                            IntPtr ptr2;
                            (strArray2 = _tabNames)[(int) (ptr2 = (IntPtr) j)] = strArray2[(int) ptr2] +
                                                                                 BitConverter.ToChar(
                                                                                     context.ReadBytes(2), 0);
                        }
                    }
                }
            }
            if ((_virtualPath != null) && (_virtualPath.Length > 1))
            {
                _isSelfReferencing = false;
            }
        }

        public override void Apply(BiffReaderWorkbookContext context)
        {
            if (_isSelfReferencing)
            {
                //context.ExternalWorkbooks.Add(context.Workbook);
                context.ExternalBookContests.Add (new ExternalBookContext(context.Workbook));
                return;
            }
            var link = new ExternalLink(context.Workbook.ExternalLinks.Count);
            var externalWorkbook = new ExternalWorkbook(link, context.Workbook.Document);
            context.ExternalBookContests.Add(new ExternalBookContext(externalWorkbook));
            link.ExternalBook = externalWorkbook;
            foreach (string name in _tabNames)
            {
                link.ExternalBook.SheetNames.Add(new ExternalSheetName {Value = name});
                link.ExternalBook.Sheets.Add(new ExternalSheet(link.ExternalBook, name));
               // externalWorkbook.Sheets.Add(new Worksheet(externalWorkbook, name));
            }
            context.Workbook.ExternalLinks.Add(link);
           // context.ExternalWorkbooks.Add(extWB);
        }

        private static string parseVirtualPath(string path)
        {
            path = path.Trim();
            if (path.StartsWith("\x0001\x0001@"))
            {
                path = path.Substring(3);
            }
            else if (path.StartsWith("\x0001\x0001"))
            {
                path = path.Substring(2, 1) + @":\" + path.Substring(3);
            }
            else if (path.StartsWith("\x0001\x0002"))
            {
                path = path.Substring(2);
            }
            else if (path.StartsWith("\x0001\x0005"))
            {
                path = path.Substring(3);
            }
            else if (path.StartsWith("\x0001\x0006"))
            {
                path = path.Substring(2);
            }
            else if (path.StartsWith("\x0001\a"))
            {
                path = path.Substring(2);
            }
            else if (path.StartsWith("\x0001\b"))
            {
                path = "file:///" + path.Substring(2);
            }
            else if (path.StartsWith("\x0001"))
            {
                path = path.Substring(1);
            }
            path = path.Replace('\x0003', '\\');
            return path;
        }
    }
}